﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Asxsyd92Core.Utils;
using WebOS.Modle;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace WebOSCore.Controllers.Api
{

    public class RouteController : Controller
    {
        [HttpGet]
        [Route("api/Route/FromJs")]
        ///
        ///生成路由配置
        ///
        public string FromJs() {
            try
            {
                //写入路由内容
                var routes = WebOS.Bll.RouteBll.Instance.GetList();
                if (routes != null)
                {
                    RunRt(routes);
                    return Newtonsoft.Json.JsonConvert.SerializeObject(new { msg = "路由生成成功！", Success = true });
                }
                return Newtonsoft.Json.JsonConvert.SerializeObject(new { msg = "没有发现路由信息，请先添加！", Success = false });
            }
            catch(Exception ex) {
                return Newtonsoft.Json.JsonConvert.SerializeObject(new { msg = ex.Message, Success = false });
            }
        }

        private void RunRt(IList<Route> routes)
        {
            string m_localPath = AppDomain.CurrentDomain.BaseDirectory;
            string path = m_localPath + "wwwroot/Common/static/js/from.js";
            Encoding code = Encoding.GetEncoding("utf-8");
            //清空From.js
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Write);
            fs.Seek(0, SeekOrigin.Begin);//文本的起点
            fs.SetLength(0);//从起点写入0个值
            fs.Close();
            var mainApp = " mainApp.config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) {  $locationProvider.hashPrefix('');$routeProvider";
            string main = " .when('{0}', {1}templateUrl: '{2}',controller: '{3}'{4})"; var mainAppend = "}]);";
            var rt = ""; var controller = "";
            foreach (var item in routes)
            {
                rt += string.Format(main, item.RouteTitle, "{", item.RouteUrl, item.Controller, "}");
                controller += string.Format("mainApp.controller('{0}', function($scope) {1});", item.Controller, "{$('.page').fadeOut();$scope.$on('$destroy', function () { Common.DestroyBaidu(); });}");
            }
            FileStream wfs = new FileStream(path, FileMode.Create);
            //获得字节数组
            byte[] data = System.Text.Encoding.UTF8.GetBytes(mainApp + rt + mainAppend + controller);
            //开始写入
            wfs.Write(data, 0, data.Length);
            //清空缓冲区、关闭流
            wfs.Flush();
            wfs.Close();
        }
        [HttpGet]
        [Route("api/Route/GetRoute")]
        public string GetRoute(string title, int page = 0, int limit = 15)
        {
            return WebOS.Bll.RouteBll.Instance.GetList(title, page, limit);
        }
        [HttpPost]
        [Route("api/Route/Insert")]
        public string Insert(string data)
        {
            var da = JsonConvert.DeserializeObject<WebOS.Modle.Route>(data);
            if (da != null)
            {
                da.ID = Guid.NewGuid();
                if (WebOS.Bll.RouteBll.Instance.Insert(da) > 0)
                {
                    return JSONhelper.ToJson(new { code = 0, msg = "保存成功", count = 1, Success = true });
                };
            }
            return JSONhelper.ToJson(new { code = 0, msg = "保存失败", count = 0, Success = false });
        }
        [HttpPost]
        [Route("api/Route/Update")]
        public string Update(string data)
        {
            var da = JsonConvert.DeserializeObject<WebOS.Modle.Route>(data);
            if (da != null)
            {

                if (WebOS.Bll.RouteBll.Instance.Update(da) > 0)
                {
                    return JSONhelper.ToJson(new { code = 0, msg = "保存成功", count = 1, Success = true });
                };
            }
            return JSONhelper.ToJson(new { code = 0, msg = "保存失败", count = 0, Success = false });
        }
        [HttpPost]
        [Route("api/Route/Delete")]
        public string Delete(Guid data)
        {
            if (WebOS.Bll.RouteBll.Instance.Delete(data) > 0)
            {
                return JSONhelper.ToJson(new { code = 0, msg = "保存成功", count = 1, Success = true });
            };
            return JSONhelper.ToJson(new { code = 0, msg = "保存失败", count = 0, Success = false });
        }
    }

}

